<template>
  <div class="app-container">
    <el-tabs v-model="activeName">
      <!--   1. 顶部操作栏-->
      <div class="filter-container">
        <el-button
          v-waves
          v-has="hasbuttons.addnewcalproject"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          @click="handleCreate"
        >
          创建计算项目
        </el-button>
        <el-button
          v-waves
          :disabled="currentCal.oid == null"
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          icon="el-icon-edit"
          @click="handleUpdateOpen"
        >
          发起计算
        </el-button>
        <el-button
          v-waves
          v-has="hasbuttons.deletecalproject"
          :disabled="currentCal.oid == null"
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          icon="el-icon-delete"
          @click="handleDeleteOpen"
        >
          删除计算项目
        </el-button>
      </div>

      <div :style="{ height: dynamicHeight }">
        <split-pane
          :min-percent="splitMinPrecent"
          :default-percent="defaultPercent"
          split="vertical"
          style="border: 1px solid #e8e8e8"
        >
          <!--   2. 左侧工作流列表-->
          <template slot="paneL">
            <span v-if="!openSide">
              <section-title
                title=""
                open-class="el-icon-caret-right"
                @changePaneL="changePaneLWith"
              />
            </span>
            <span v-else>
              <section-title
                title="工作流列表"
                open-class="el-icon-caret-left"
                @changePaneL="changePaneLWith"
              />
              <work-flow-tree
                :current-node-key="currentNodeKey"
                :data-source="dataSource.records"
                node-key="oid"
                :default-props="defaultProps"
                @change="clickNode"
              ></work-flow-tree>
            </span>
          </template>

          <!--   3. 工作流流程图页面-->
          <template v-if="!isCalItemDetail && !titlePage" slot="paneR">
            <div ref="flowmap">
              <section-title title="流程图" />
              <div id="rap" class="rap-class"></div>
            </div>
          </template>

          <!--   4. 计算项目详情页面-->
          <template v-if="isCalItemDetail && !titlePage" slot="paneR">
            <calculation-item-detail
              ref="detail"
              :calculate-data="calItemData"
              :all-activities="allActivities"
              :current-activities="currentActivities"
              :product-data="productData"
              @change="handleAction"
            ></calculation-item-detail>
          </template>

          <!--   5. 点击一级标题页面 todo-->
          <template v-if="titlePage" slot="paneR">
            <div>这是首页，点左边工作流、计算项目test 004查看详情</div>
          </template>
        </split-pane>
      </div>
    </el-tabs>

    <!-- dia 1. 创建计算项目模态框-->
    <div class="dia">
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="open_create"
        width="56%"
      >
        <template slot="title">
          <div class="titleZise">
            <svg-icon icon-class="flow7-add" />
            <span>创建计算项目</span>
          </div>
        </template>
        <el-form style="color: #1f2d3d" :rules="rules" label-width="auto">
          <el-form-item label="所属工作流" prop="workFlowID">
            <el-select v-model="calParam.workFlowID">
              <el-option
                v-for="item in wfList"
                :key="item.oid"
                :label="item.name"
                :value="item.oid"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计算项目名称" prop="name">
            <el-input v-model="calParam.name"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="calParam.description" type="textarea"></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="createCal">确 定</el-button>
          <el-button @click="open_create = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <!--  dia 2. 发起计算模态框-->
    <div class="dia">
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="open_start"
        width="800px"
      >
        <template slot="title">
          <div class="titleZise">
            <svg-icon icon-class="flow7-add" />
            <span>发起计算</span>
          </div>
        </template>
        <el-form style="color: #1f2d3d">
          <el-form-item>
            <el-row>
              <el-col :span="4">计算项目ID：</el-col>
              <el-col :span="20">
                <el-input v-model="currentCal.oid" disabled readonly></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :span="4">计算项目名称：</el-col>
              <el-col :span="20">
                <el-input
                  v-model="currentCal.name"
                  disabled
                  readonly
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :span="4">请选择阶段：</el-col>
              <el-col :span="20">
                <el-select v-model="calParam.category">
                  <el-option
                    v-for="item in dataSource.records"
                    :key="item.type"
                    :label="item.type"
                    :value="item.type"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :span="4">描述：</el-col>
              <el-col :span="20">
                <el-input
                  v-model="currentCal.description"
                  type="textarea"
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleUpdate">确 定</el-button>
          <el-button @click="open_start = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <!--  dia 3. 删除计算模态框-->
    <div class="dia">
      <el-dialog
        :close-on-click-modal="false"
        title="删除计算"
        :visible.sync="open_delete"
        width="800px"
      >
        <template slot="title">
          <div class="titleZise">
            <svg-icon icon-class="flow7-add" />
            <span>删除计算</span>
          </div>
        </template>
        <el-form style="color: #1f2d3d">
          <el-form-item>
            <el-row>
              <el-col :span="4">计算项目ID：</el-col>
              <el-col :span="20">
                <el-input v-model="currentCal.oid" disabled readonly></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :span="4">计算项目名称：</el-col>
              <el-col :span="20">
                <el-input
                  v-model="currentCal.name"
                  disabled
                  readonly
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item>
            <el-row>
              <el-col :span="4">计算项目发起人：</el-col>
              <el-col :span="20">
                <el-input
                  v-model="currentCal.createUser"
                  disabled
                  readonly
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item>
            <el-row>
              <el-col :span="4">描述：</el-col>
              <el-col :span="20">
                <el-input
                  v-model="currentCal.description"
                  type="textarea"
                  disabled
                  readonly
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleDelete">确 定</el-button>
          <el-button @click="open_start = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <!--  dia 4. 审批模态框-->
    <div class="dia">
      <el-dialog
        :close-on-click-modal="false"
        title="审批意见"
        :visible.sync="open_approve"
        width="500px"
      >
        <template slot="title">
          <div class="titleZise">
            <svg-icon icon-class="flow7-add" />
            <span>审批意见</span>
          </div>
        </template>
        <el-form style="color: #1f2d3d">
          <el-form-item>
            <el-row style="text-align: center">
              <el-col :span="24">
                <el-radio-group
                  v-model="approveData.approveComments"
                  size="medium"
                >
                  <el-radio label="1" border>通过</el-radio>
                  <el-radio label="2" border>不通过</el-radio>
                </el-radio-group>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :span="4">审核意见：</el-col>
              <el-col :span="20">
                <el-input
                  v-model="approveData.approveDescription"
                  type="textarea"
                ></el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="approve_sumbit">确 定</el-button>
          <el-button @click="open_approve = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import splitPane from 'vue-splitpane'
  import sectionTitle from '@/components/SectionTitle'
  import { getAction, postAction, deleteAction } from '@/api/action'
  import { BaseListMixin } from '@/mixins/BaseListMixin'
  import WorkFlowTree from '@/views/calculate-project/compoents/WorkFlowTree'
  import CalculationItemDetail from '@/views/calculate-project/compoents/CalculationItemDetail'
  import { initRaphael } from '@/utils/PreWebRaphaelTools'
  import { MessageBox } from 'element-ui'
  const hasbuttons = {
    addnewcalproject: 'Calculation:createCalProject',
    deletecalproject: '',
  }
  export default {
    name: 'LoadWorkflowCalculation',
    components: {
      CalculationItemDetail,
      WorkFlowTree,
      splitPane,
      sectionTitle,
    },
    mixins: [BaseListMixin],
    data() {
      return {
        hasbuttons: hasbuttons,
        splitMinPrecent: 12,
        defaultPercent: 25,
        dataSource: {
          records: [],
        },
        open_create: false, //是否打开创建计算项目模态框
        open_start: false, //是否打开发起计算模态框
        open_delete: false, //是否打开删除计算模态框

        open_approve: false, //是否打开审批模态框
        approveData: {
          approveComments: '1',
          approveDescription: '',
        }, //审批活动数据
        approveItem: {},

        openSide: true,
        filterText: '',
        // currentCheckNodeData: {},
        activeName: 'first',
        defaultProps: {
          children: 'children',
          label: 'wfName',
        },
        workFlowBaseInfo: {
          preId: '编号',
          name: '名称',
          category: '分类',
          createUser: '所有者',
        },
        url: {
          list:
            '/presoftasim/calculateProject/loadWorkflowCalculation/treeList',
          detail: 'presoftasim/wf/workflow/detail',
          createCal: '/presoftasim/calculate/wfproject/create',
          deleteCal: '/presoftasim/calculate/wfproject/delete',
          activityList: '/presoftasim/calculate/activity/activityList',
          startCal: '/presoftasim/calculate/wfproject/start',
          pauseCal: '/presoftasim/calculate/wfproject/pause',
          stopCal: '/presoftasim/calculate/wfproject/stop',
          restartCal: '/presoftasim/calculate/wfproject/restart',
          graph: '/presoftasim/wf/workflow/graphData',
          allActivitiesUrl:
            '/presoftasim/calculate/activity/allActivityByCalculateId',
          currentActivitiesUrl:
            '/presoftasim/calculate/activity/currentByCalculateId',
          projectStatusUrl: '/presoftasim/calculate/wfproject/projectStatus',
          approvalUrl: '/presoftasim/calculate/activity/approval',
          productsList: '/presoftasim/calculate/activity/getProductByWfProject',
        },
        rules: {
          workFlowID: [{ required: true, trigger: 'blur' }],
          name: [{ required: true, trigger: 'blur' }],
        },
        disableMixinCreated: true,

        titlePage: true, //当前是否标题页面
        isCalItemDetail: false, //当前是否计算项目详情页面
        calItemData: {}, //计算项目详情页面数据
        wfList: [], //工作流列表
        currentCal: {}, //当前选中的计算项目
        productData: [], // 当前计算项目的全部产品
        currentWerkFlow: {}, //当前选中的工作流
        calParam: {
          //计算项目参数
          id: this.$store.state.user.id,
          userName: this.$store.state.user.name,
          workFlowID: '',
          description: '',
          category: '',
          name: '',
          oid: '',
        },
        // currentActivities: [],              //计算项目当前活动列表
        activityParam: {
          //当前计算项目活动请求参数
          id: this.$store.state.user.id,
          userName: this.$store.state.user.name,
          oid: '',
        },
        modelIcon: {
          //模态框图标
          create: 'el-icon-document-add',
          update: 'el-icon-edit-outline',
          detail: 'el-icon-document-copy',
        },
        currentNodeKey: '', //当前选中节点oid
        projectStatusMap: new Map(), // 计算项目状态

        // 子组件中使用的值
        allActivities: [],
        currentActivities: [],
      }
    },
    computed: {
      dynamicHeight: function () {
        // 40是box的margin-top和margin-bottom  35是页脚 footer高度
        return window.innerHeight > 710
          ? window.innerHeight - 40 - 35 + 'px'
          : '710px'
      },
      getStageType: function () {
        //根据workFlowID获取category
        for (let i in this.wfList) {
          if (this.calParam.workFlowID == this.wfList[i].oid) {
            return this.wfList[i].stageType
          }
        }
        return ''
      },
    },
    created() {
      this.getList()
      this.getProjectStatusEnum()
    },
    methods: {
      // 模块title展示  最好调整到computed中
      changePaneLWith() {
        this.openSide = !this.openSide
        if (this.openSide) {
          this.splitMinPrecent = 12
          this.defaultPercent = 25
        } else {
          this.splitMinPrecent = (150 / window.innerWidth) * 30
          this.defaultPercent = (150 / window.innerWidth) * 30
        }
      },

      // 枚举类 -- 获取计算项目所有的状态[初始化加载]
      getProjectStatusEnum() {
        let that = this
        getAction(this.url.projectStatusUrl, {}).then((res) => {
          if (res.code == 200) {
            that.projectStatusMap = res.data
          }
        })
      },

      //获取工作流、计算项目数据[初始化调用]
      getList() {
        getAction(this.url.list, {}).then((res) => {
          this.dataSource = res.data
        })
      },

      //右侧tree组件中触发点击事件
      clickNode(data) {
        console.log(data)
        this.calItemData = data
        this.titlePage = false // 一级菜单设置为true
        this.currentWerkFlow = {} // 二级菜单时  选中的工作流
        this.currentCal = {} // 三级菜单时  选中的时计算项目
        this.isCalItemDetail = false
        if (data.objectType === 'classify') {
          //二级菜单
          this.currentWerkFlow = data
          this.isCalItemDetail = false
          this.graphFlow('rap', data.oid)
        } else if (data.objectType === 'guide') {
          //三级菜单
          this.currentCal = data
          this.isCalItemDetail = true
          this.getCurrentActivities(data.oid)
          this.getAllActivities(data.oid)
          // 获得当前计算项目全部的产品
          this.getProductData(data.oid)
        } else if (data.objectType === 'title') {
          //一级菜单
          this.titlePage = true
          this.currentWerkFlow = {}
          this.isCalItemDetail = false
        }
      },
      // 获得当前计算项目全部的产品
      getProductData(oid) {
        getAction(this.url.productsList, { oid: oid }).then((res) => {
          if (res.code == 200) {
            this.productData = res.data
          }
        })
      },
      // 获取当前活动列表
      getCurrentActivities(oid) {
        let that = this
        getAction(this.url.currentActivitiesUrl, { oid: oid }).then((res) => {
          if (res.code == 200) {
            that.currentActivities = res.data
          } else {
            this.submitFail(res.message)
          }
        })
      },

      // 点击查询全部活动
      getAllActivities(oid) {
        getAction(this.url.allActivitiesUrl, { oid: oid }).then((res) => {
          if (res.code == 200) {
            this.allActivities = res.data
          } else {
            this.submitFail(res.message)
          }
        })
      },

      // 绘制流程图
      graphFlow(ref, oid) {
        getAction(this.url.graph, { workFlowId: oid }).then((res) => {
          // initRaphael('rap', [])
          initRaphael(ref, [res.data])
        })
      },
      //  获取所有工作流列表[下拉框查询]
      getWFList: function () {
        this.wfList = []
        for (let i in this.dataSource.records) {
          this.wfList.push.apply(
            this.wfList,
            this.dataSource.records[i].children
          )
        }
      },

      /*
       * -----'计算项目操作模块'----
       */
      // 计算项目详情，各个事件处理函数
      handleAction: function (params) {
        if (params.method == 'start') {
          this.handleStart(params.data)
        } else if (params.method == 'pause') {
          this.handlePause(params.data)
        } else if (params.method == 'stop') {
          this.handleStop(params.data)
        } else if (params.method == 'restart') {
          this.handlRestart(params.data)
        } else if (params.method == 'currentActivities') {
          this.getCurrentActivities(this.currentCal.oid)
        } else if (params.method == 'approval') {
          this.open_approve = true
          this.approveItem = params.data
        } else if (params.method == 'initRap') {
          this.graphFlow('graphDiv', params.currentWorkFlowOid)
        }
      },
      //1. 计算项目详情，开始事件函数
      handleStart: function (data) {
        MessageBox.confirm('是否确认发起该计算项目！', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'info',
        }).then(() => {
          getAction(this.url.startCal, data).then((res) => {
            if (res.code == 200) {
              // 更新计算项目信息 -- 状态发生了改变
              this.calItemData.status = this.projectStatusMap['processing']
              this.getAllActivities(this.currentCal.oid)
              this.getCurrentActivities(this.currentCal.oid)
            } else {
              this.submitFail(res.message)
            }
          })
        })
      },
      //2. 计算项目详情，暂停事件函数
      handlePause: function (data) {
        MessageBox.confirm('是否确认暂停该计算项目！', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'info',
        }).then(() => {
          getAction(this.url.pauseCal, data).then((res) => {
            if (res.code == 200) {
              // 更新计算项目信息 -- 状态发生了改变
              this.calItemData.status = this.projectStatusMap['pause']
              this.getAllActivities(this.currentCal.oid)
              this.getCurrentActivities(this.currentCal.oid)
            } else {
              this.submitFail(res.message)
            }
          })
        })
      },
      //3. 计算项目详情，停止事件函数
      handleStop: function (data) {
        MessageBox.confirm('是否确认停止该计算项目！', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'info',
        }).then(() => {
          getAction(this.url.stopCal, data).then((res) => {
            if (res.code == 200) {
              // this.getList();
              // 更新计算项目信息 -- 状态发生了改变
              this.calItemData.status = this.projectStatusMap['stop']

              this.getAllActivities(this.currentCal.oid)
              this.getCurrentActivities(this.currentCal.oid)
            } else {
              this.submitFail(res.message)
            }
          })
        })
      },
      //4. 计算项目详情，重新开始事件函数
      handlRestart: function (data) {
        MessageBox.confirm('是否确认重新开始该计算项目！', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'info',
        }).then(() => {
          getAction(this.url.restartCal, data).then((res) => {
            if (res.code == 200) {
              // this.getList();
              // 更新计算项目信息 -- 状态发生了改变
              this.calItemData.status = this.projectStatusMap['PROCESSING']
              this.getAllActivities(this.currentCal.oid)
              this.getCurrentActivities(this.currentCal.oid)
            } else {
              this.submitFail(res.message)
            }
          })
        })
      },

      // 审核活动提交
      approve_sumbit() {
        let approveObj = Object.assign({}, this.approveItem, this.approveData)
        this.open_approve = false
        getAction(this.url.approvalUrl, approveObj).then((res) => {
          if (res.code == 200) {
            this.getCurrentActivities(this.currentCal.oid)
          } else {
            this.submitFail(res.message)
          }
        })
      },

      /*
       * -----'顶部按钮操作各个函数'-----
       */
      //打开创建计算项目模态框
      handleCreate: function () {
        this.getWFList()
        this.open_create = true
      },
      //创建新的计算项目(模态框)
      createCal: function () {
        this.calParam.stageType = this.getStageType
        postAction(this.url.createCal, this.calParam).then((res) => {
          if (res.code == 200) {
            this.getList()
          } else {
            this.submitFail(res.message)
          }
        })

        this.open_create = false
      },

      //打开发起计算模态框
      handleUpdateOpen: function () {
        this.open_start = true
      },
      //打开删除计算项目模态框
      handleDeleteOpen: function () {
        this.open_delete = true
      },
      //删除计算项目
      handleDelete: function () {
        this.calParam.oid = this.currentCal.oid
        deleteAction(this.url.deleteCal, this.calParam).then((res) => {
          if (res.code === 200) {
            this.getList()
          } else {
            this.submitFail(res.message)
          }
        })
        this.open_delete = false
      },

      /*
       * -------'其他模态框操作'--------
       */
      //打开审核模态框
      // approve_open: function(data){
      //   this.approveData=data;
      //   this.open_approve=true;
      // },
      //退出模态框
      // approve_cancel: function(){this.open_approve=false;},

      // 下一步活动下一步
      // @nextStep="nextStep"
      // nextStep: function (item) {
      //   alert(item.oid);
      // }

      // 获取当前活动列表
      // getCurrentActivities(oid){
      //   let that = this;
      //
      //   return new Promise((resolve, reject) => {
      //     getAction(that.url.currentActivitiesUrl, {'oid':oid}).then(res => {
      //       console.log(that.currentActivities.length);
      //       that.currentActivities = res.data;
      //     });
      //   })
      //
      // },

      // tab页面切换事件
      // handleClick(tab, event) {
      //   console.log(tab, event);
      // },

      //获取跳转地址传递的参数
      // getQuery: function () {
      //   if (this.$route.query != null) {
      //     console.log(this.$route.query);
      //   }
      // },

      //模态框取消按钮
      // cancel:function () {
      //   this.open_create = false;
      //   this.open_start = false;
      //   this.open_delete = false;
      // },
    },
  }
</script>
<style lang="scss" scoped>
  .rap-class {
    overflow: auto;
    height: 100%;
  }
  .vue-splitter-container {
    height: 100%;
  }
</style>
